package com.gxh.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.util.List;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }

    /**
     * 判断文件是否存在
     *
     * @param objectName
     * @return
     */
    public boolean doesObjectExist(String objectName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            return ossClient.doesObjectExist(bucketName, objectName);
        } catch (OSSException | ClientException e) {
            log.warn("检测 OSS 文件是否存在时发生异常，objectName = {}, 错误 = {}", objectName, e.getMessage());
            // 出错时默认认为文件不存在，避免上传中断
            return false;
        } finally {
            ossClient.shutdown();
        }
    }


    /**
     * 获取文件访问路径
     *
     * @param objectName
     * @return
     */
    public String getFileUrl(String objectName) {
        return "https://" + bucketName + "." + endpoint + "/" + objectName;
    }

    /**
     * 批量删除 OSS 文件（最多1000个）
     * @param objectNames 要删除的文件 key 列表
     */
    public void deleteBatchOss(List<String> objectNames) {
        log.info("准备删除文件：{}", objectNames);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            if (objectNames == null || objectNames.isEmpty()) {
                log.warn("未传入任何要删除的文件 key");
                return;
            }

            DeleteObjectsRequest deleteRequest = new DeleteObjectsRequest(bucketName)
                    .withKeys(objectNames)
                    .withQuiet(false); // ❗关键：关闭 quiet，返回真实删除结果

            // 获取删除结果
            List<String> deletedObjects = ossClient.deleteObjects(deleteRequest).getDeletedObjects();

            log.info("批量删除成功，实际删除 {} 个文件，文件名：{}", deletedObjects.size(), deletedObjects);
        } catch (Exception e) {
            log.error("批量删除 OSS 文件出错: {}", e.getMessage(), e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 从 OSS 完整访问链接中提取 objectName（去除域名）
     * @param url 如：https://your-bucket.oss-cn-xxx.aliyuncs.com/folder/image.jpg
     * @return objectName，如 folder/image.jpg
     */
    public String extractObjectName(String url) {
        int index = url.indexOf(".com/");
        return index != -1 ? url.substring(index + 5) : url;
    }

}
